import serial
import paho.mqtt.client as mqtt_client
from paho.mqtt.client import CallbackAPIVersion
import json
import random

# 配置串口
SERIAL_PORT = 'COM5'  # 接收端使用的串口（应与 sender 不同）
BAUD_RATE = 9600

# MQTT 配置
MQTT_BROKER = "127.0.0.1"
MQTT_PORT = 1883
MQTT_TOPIC = "iot/sensor/data"

CLIENT_ID = f"data_publisher_{random.randint(0, 1000)}"

# 创建mqtt客户端，接mqtt代理
def connect_mqtt():
    client = mqtt_client.Client(
        callback_api_version=CallbackAPIVersion.VERSION2,
        client_id=CLIENT_ID
    )
    client.connect(MQTT_BROKER, MQTT_PORT)
    return client


def run():
    mqtt_pub = connect_mqtt()
    try:
        with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
            print(f"[串口] 监听串口 {SERIAL_PORT} ...")

            buffer = ""
            while True:
                if ser.in_waiting > 0:
                    chunk = ser.read(ser.in_waiting).decode('utf-8')
                    buffer += chunk

                    # 分割完整的消息
                    lines = buffer.split('\n')
                    for line in lines[:-1]: # 遍历数据
                        try:
                            data = json.loads(line)
                            print(f"[串口] 收到数据: {line}")
                            mqtt_pub.publish(MQTT_TOPIC, line)
                            print("✅ 已发布到 MQTT")
                        except json.JSONDecodeError:
                            print(f"[错误] 解析失败: {line}")

                    buffer = lines[-1]  # 剩余部分保留
    except serial.SerialException as e:
        print(f"[错误] 串口接收失败: {e}")


if __name__ == '__main__':
    run()